package com.filldream.fastboot.common.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.filldream.fastboot.common.entity.db.HolidayDTO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Data
public class HolidayUtil {

    /**
     * 获取指定年份的节假日信息
     * 注意:此接口可能会出现超时的情况，且非常不问题，建议使用浏览器请求后调用analysisJson方法解析数据
     * @param year   年份
     * @return    节假日信息列表
     */
    public static List<HolidayDTO> holidayByYear(String year){
        log.info("开始获取{}年节假日信息", year);
        List<HolidayDTO> resultList = new ArrayList<>();
        HttpRequest httpRequest = HttpUtil.createGet("https://timor.tech/api/holiday/year?data="+year+"&dfd=" + RandomUtil.randomUUID());
        httpRequest.header("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
        httpRequest.header("Accept-Encoding","gzip, deflate");
        httpRequest.header("Accept-Language","zh-CN,zh;q=0.9");
        httpRequest.header("Cache-Control","max-age=0");
        httpRequest.header("Host","timor.tech");
        httpRequest.header("If-Modified-Since","Tue, 03 Dec 2024 23:25:16 GMT");
        httpRequest.header("Proxy-Connection","keep-alive");
        httpRequest.header("Upgrade-Insecure-Requests","1");
        httpRequest.header("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36");

        String json = httpRequest.execute().body();
        log.info("已经获取{}年节假日信息：{}", year, json);
        return analysisJson(json);
    }

    /**
     * 解析原生接口返回的json数据
     * @param apiResultJson
     * @return
     */
    public static List<HolidayDTO> analysisJson(String apiResultJson){
        List<HolidayDTO> resultList = new ArrayList<>();
        JSONObject jsonObject = JSONObject.parseObject(apiResultJson);
        if( !jsonObject.getInteger("code").equals(0) ){
            return null;
        }
        JSONObject holidayList = jsonObject.getJSONObject("holiday");
        holidayList.entrySet().forEach(entry -> {
            String date = entry.getValue().toString();
            HolidayDTO holidayDTO = JsonUtil.fromJson(date, HolidayDTO.class);
            resultList.add(holidayDTO);
        });
        return resultList;
    }

}
